import PureHttp from './request'
import { downloadBlob } from './download'
import { ElLoading } from 'element-plus'
import { blobValidate } from '../common'
import { message } from '../message'

const http = new PureHttp()

/**
 * 导出文件通用下载方法
 * @param url 请求路径
 * @param params 请求参数
 * @param filename 文件名
 * @param config 其他参数
 * @returns
 */
export function downloadFile(
  url: string,
  params: any,
  filename: string,
  config?: any,
  method: 'post' | 'get' = 'post'
) {
  const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    default: '系统未知错误，请反馈给管理员',
  }

  const downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  return http[method](
    url,
    { params },
    {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    }
  )
    .then(async (data: any) => {
      const isLogin = await blobValidate(data)
      if (isLogin) {
        const blob = new Blob([data.data])
        downloadBlob(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        message(errMsg, { type: 'error' })
      }
      downloadLoadingInstance.close()
    })
    .catch((r) => {
      console.error(r)
      message('下载文件出现错误，请联系管理员！', { type: 'error' })
      downloadLoadingInstance.close()
    })
}

export { http, downloadBlob }
